package com.yanqu.road.server.manger.activity.drink;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.drink.DrinkOrder;
import com.yanqu.road.entity.activity.drink.DrinkOrderProg;
import com.yanqu.road.entity.activity.drink.config.DrinkConfig;
import com.yanqu.road.entity.activity.drink.config.DrinkOrderConfig;
import com.yanqu.road.entity.activity.drink.config.DrinkScoreConfig;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.bussiness.activity.DrinkActivityBusiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.drink.DrinkModule;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.RandomHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DrinkMgr extends TempMgr {

    private static DrinkConfig drinkConfig;


    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static DrinkConfig getDrinkConfig() {
        return drinkConfig;
    }

    public static ActivityInfo getActivityInfo() {
        return drinkConfig == null ? null : drinkConfig.getActivityInfo();
    }

    public static void reloadActivityData() {

        getLogger().info("reload DrinkActivity start");

        // 获取进行中的活动信息
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.DrinkActivity.getValue());
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no DrinkActivity in show time");
            drinkConfig = null;
            return;
        }

        DrinkConfig tmpConfig = new DrinkConfig();
        tmpConfig.setActivityInfo(openActivityInfoList.get(0));
        int tmpActivityId = tmpConfig.getActivityInfo().getActivityId();

        // 配置表配置
        tmpConfig.setBlockConfigMap(DrinkActivityBusiness.getDrinkBlockConfigMap(tmpActivityId));
        tmpConfig.setOrderConfigMap(DrinkActivityBusiness.getDrinkOrderConfigMap(tmpActivityId));
        tmpConfig.setScoreConfigMap(DrinkActivityBusiness.getDrinkScoreConfigMap(tmpActivityId));

        // config配置
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);
        tmpConfig.setScoreItemId(activityConfigMap.get(eActivityConfigType.DRINK_SCORE_ITEM_ID.getName()).getIntValue());
        tmpConfig.setEnergyRecItemId(activityConfigMap.get(eActivityConfigType.DRINK_ENERGY_ITEM_ID.getName()).getIntValue());
        List<Integer> energyParam = activityConfigMap.get(eActivityConfigType.DRINK_ENERGY_PARAM.getName()).getIntListValue(";");
        tmpConfig.setMaxEnergy(energyParam.get(0));
        tmpConfig.setEnergyRecTime(energyParam.get(1) * 1000L);
        tmpConfig.setEnergyRecCount(energyParam.get(2));
        tmpConfig.setBlockWeightList(activityConfigMap.get(eActivityConfigType.DRINK_CREATE_BLOCK_WEIGHT_LIST.getName()).getIntListValue(";"));
        tmpConfig.setEliminateScoreList(activityConfigMap.get(eActivityConfigType.DRINK_ELIMINATE_SCORE_PRAM.getName()).getIntListValue(";"));
        tmpConfig.setMultiUnlockScore(activityConfigMap.get(eActivityConfigType.DINK_MULTI_UNLOCK_SCORE.getName()).getIntValue());
        List<Integer> guideParam = activityConfigMap.get(eActivityConfigType.DRINK_GUIDE_PARAM.getName()).getIntListValue(";");
        tmpConfig.setGuideOrderId(guideParam.get(0));
        List<Integer> initBlock = activityConfigMap.get(eActivityConfigType.DRINK_INIT_BLOCK.getName()).getIntListValue(",");
        int[] tmpBlockList = initBlock.stream().mapToInt(item -> item).toArray();
        tmpConfig.setInitBlock(tmpBlockList);
        List<Integer> initBlockMulti = activityConfigMap.get(eActivityConfigType.DRINK_INIT_BLOCK_MULTI.getName()).getIntListValue(",");
        int[] tmpBlockListMulti = initBlockMulti.stream().mapToInt(item -> item).toArray();
        tmpConfig.setInitBlockMulti(tmpBlockListMulti);
        tmpConfig.setMultiUnlockVipLevel(activityConfigMap.get(eActivityConfigType.DINK_MULTI_UNLOCK_VIP_LEVEL.getName()).getIntValue());
        tmpConfig.setCostEnergyList(activityConfigMap.get(eActivityConfigType.DRINK_COST_ENERGY_PARAM.getName()).getIntListValue(";"));

        if (activityConfigMap.containsKey(eActivityConfigType.DINK_FAST_UNLOCK_VIP_LEVEL.getName())) {
            tmpConfig.setFastUnlockVipLevel(activityConfigMap.get(eActivityConfigType.DINK_FAST_UNLOCK_VIP_LEVEL.getName()).getIntValue());
            List<Integer> initBlockFast = activityConfigMap.get(eActivityConfigType.DRINK_INIT_BLOCK_FAST.getName()).getIntListValue(",");
            int[] tmpBlockListFast = initBlockFast.stream().mapToInt(item -> item).toArray();
            tmpConfig.setInitBlockFast(tmpBlockListFast);
        } else {
            // 旧活动没配置不让用
            tmpConfig.setFastUnlockVipLevel(Integer.MAX_VALUE);
            tmpConfig.setInitBlockFast(new int[42]);
        }

        // 组装下订单积分配置
        for (DrinkOrderConfig orderConfig : tmpConfig.getOrderConfigMap().values()) {
            orderConfig.setReward(tmpConfig.getScoreItemId() + "=" + orderConfig.getReward());
        }

        drinkConfig = tmpConfig;

        getLogger().info("reload DrinkActivity finish");

        // 在线玩家下发数据
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            DrinkModule module = gamePlayer.getModule(DrinkModule.class);
            module.syncConfig();
            module.initUserData();
            module.syncUserData();
        }
    }

    /**
     * 获取随机订单ID
     */
    public static int getRandomOrderId(int multi) {
        List<Integer> idList;
        List<Integer> weightList;
        int index;

        // 随机订单
        idList = new ArrayList<>();
        weightList = new ArrayList<>();
        for (DrinkOrderConfig orderConfig : drinkConfig.getOrderConfigMap().values()) {
            if (orderConfig.getMulti() == 0 && multi == 1
                    || orderConfig.getMulti() == 1 && multi == 8
                    || orderConfig.getMulti() == 2 && multi == 16) {
                idList.add(orderConfig.getOrderId());
                weightList.add(orderConfig.getWeight());
            }
        }
        index = RandomHelper.getRandomIndexByWeight(weightList);
        DrinkOrderConfig orderConfig = drinkConfig.getOrderConfigMap().get(idList.get(index));

        return orderConfig.getOrderId();
    }

    /**
     * 创建特定订单
     */
    public static DrinkOrder createOrder(int orderId) {
        // 获取配置
        DrinkOrderConfig orderConfig = drinkConfig.getOrderConfigMap().get(orderId);

        DrinkOrder order = new DrinkOrder();
        order.setoId(orderConfig.getOrderId());
        order.setStep(0);
        order.setMaxStep(orderConfig.getMaxTimes());

        Map<Integer, DrinkOrderProg> progMap = new ConcurrentHashMap<>();
        List<Integer> numList = orderConfig.getNumList();
        List<Integer> blockList = orderConfig.getBlockList();
        for (int i = 0; i < numList.size(); i++) {
            progMap.put(blockList.get(i), new DrinkOrderProg(blockList.get(i), numList.get(i), 0));
        }
        order.setProgMap(progMap);

        order.setReward(orderConfig.getReward());

        return order;
    }

    /**
     * 计算第x轮的格子积分（x从1开始）
     */
    public static long calBlockScore(int round, int multi) {
        // 基础积分
        BigDecimal baseScore = BigDecimal.valueOf(drinkConfig.getEliminateScoreList().get(multi == 16 ? 2 : multi == 8 ? 1 : 0));
        // 放大倍数
        int scoreAdd = 0;
        Map<Integer, DrinkScoreConfig> scoreConfigMap = getDrinkConfig().getScoreConfigMap();
        if (scoreConfigMap.containsKey(round)) {
            scoreAdd = scoreConfigMap.get(round).getScoreAdd();
        } else {
            // 没有配置的话，就取最大值
            int maxRound = -1;
            for (DrinkScoreConfig scoreConfig : scoreConfigMap.values()) {
                if (scoreConfig.getContinuousNum() > maxRound) maxRound = scoreConfig.getContinuousNum();
            }
            scoreAdd = scoreConfigMap.get(maxRound).getScoreAdd();
        }
        // 结果
        return baseScore.multiply(BigDecimal.valueOf(1000 + scoreAdd)).divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).longValue();
    }

    /**
     * 判断订单状态
     *
     * @return 1进行中，2已完成，3失败
     */
    public static int checkOrderStatus(DrinkOrder copyOrder) {
        boolean finish = true;
        for (DrinkOrderProg orderProg : copyOrder.getProgMap().values()) {
            if (orderProg.getCur() < orderProg.getNeed()) {
                finish = false;
                break;
            }
        }

        boolean stepMax = copyOrder.getStep() >= copyOrder.getMaxStep();

        if (stepMax) {
            return finish ? 2 : 3;
        } else {
            return finish ? 2 : 1;
        }
    }

    /**
     * 补充（修复）后续订单数据
     */
    public static void checkOrderIdList(List<Integer> orderIdList, int multi) {
        // 有问题的删了
        Map<Integer, DrinkOrderConfig> configMap = getDrinkConfig().getOrderConfigMap();
        for (int i = orderIdList.size() - 1; i >= 0; i--) {
            if (i > 2 || !configMap.containsKey(orderIdList.get(i))) {
                orderIdList.remove(i);
            }
        }
        // 少的加上去
        for (int i = orderIdList.size(); i <= 2; i++) {
            orderIdList.add(getRandomOrderId(multi));
        }
    }

    // =======================================================================

    /**
     * 复制一份格子数据
     */
    public static int[][] getCopyBlockList(int[][] list) {
        int[][] result = new int[list.length][];
        for (int i = 0; i < list.length; i++) {
            result[i] = list[i].clone();
        }
        return result;
    }

    /**
     * 复制一份订单
     */
    public static DrinkOrder getCopyDrinkOrder(DrinkOrder order) {
        DrinkOrder tmpOrder = new DrinkOrder();
        tmpOrder.setoId(order.getoId());
        tmpOrder.setStep(order.getStep());
        tmpOrder.setMaxStep(order.getMaxStep());

        Map<Integer, DrinkOrderProg> progMap = new ConcurrentHashMap<>();
        for (DrinkOrderProg orderProg : order.getProgMap().values()) {
            progMap.put(orderProg.getbId(), new DrinkOrderProg(orderProg.getbId(), orderProg.getNeed(), orderProg.getCur()));
        }
        tmpOrder.setProgMap(progMap);

        tmpOrder.setReward(order.getReward());
        return tmpOrder;
    }

}
